package com.qf.blog.controller;

import com.qf.blog.auth.LoginThreadLocal;
import com.qf.blog.constatns.LoginConstatns;
import com.qf.blog.entity.Comment;
import com.qf.blog.entity.DiscussPost;
import com.qf.blog.entity.User;
import com.qf.blog.service.ICommentService;
import com.qf.blog.service.IDiscussPostService;
import com.qf.blog.service.IUserService;
import com.qf.blog.service.impl.FollowerService;
import com.qf.blog.utils.Result;
import com.qf.blog.vo.CommentVo;
import com.qf.blog.vo.PostVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author toString
 * @since 2024-05-21
 */
@Controller
@RequestMapping("/discussPost")
public class DiscussPostController {
    @Autowired
    private IDiscussPostService postService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private FollowerService followerService;

    public String list(Model model){
        List<DiscussPost> list = postService.list();
        model.addAttribute("postList",list);
        return "xxxList";
    }

    @RequestMapping("/publish")
    @ResponseBody
    public Result publish(@RequestBody DiscussPost post){
        User loginUser = LoginThreadLocal.get();


        post.setUserId(loginUser.getId());
        post.setStatus(0);
        post.setType(0);
        post.setCreateTime(new Date());

        boolean save = postService.save(post);
        if(save){
            return Result.success();
        }
        return Result.error("发布失败");
    }

    @RequestMapping("/info/{postId}")
    public String info (@PathVariable Integer postId, Model model){
        DiscussPost post = postService.getById(postId);

        User user = userService.getById(post.getUserId());

        List<CommentVo> comments = commentService.getCommentListByPostId(post);

        Long starsCount = followerService.getStartCount(1,postId);

        Integer isStars = followerService.IsStars(1, postId);

        PostVo postVo = new PostVo();
        postVo.setPost(post);
        postVo.setUser(user);
        postVo.setCommentVos(comments);
        postVo.setStarsCount(starsCount);
        postVo.setIsStarts(isStars);

        model.addAttribute("postVo", postVo);
        return "site/discuss-detail";
    }

}
